


import { Http, Headers, Jsonp, } from '@angular/http';
import { Injectable } from '@angular/core';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import * as moment from 'moment';
import {CosCloud,CryptoJS} from 'cos-js-sdk-v5';
import * as COS from 'cos-js-sdk-v5/src/cos.js'
@Injectable()

export class UploadService {

    constructor(public http: Http, public jsonp: Jsonp, ) {
        this.http = http;
        
    }




    upload(file, callback){
        // 请求用到的参数
        var Bucket = 'blog-1253223675';
        var Region = 'ap-guangzhou';
        var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
        var prefix = protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com/';

        // 计算签名
        var getAuthorization = function (options, callback) {
            // 方法一（适用于前端调试）
            // var method = (options.Method || 'get').toLowerCase();
            // var key = options.Key || '';
            // var pathname = key.indexOf('/') === 0 ? key : '/' + key;
            // var url = '../server/auth.php?method=' + method + '&pathname=' + encodeURIComponent(pathname);
            // var xhr = new XMLHttpRequest();
            // xhr.open('GET', url, true);
            // xhr.onload = function (e) {
            //     callback(null, e.target.responseText);
            // };
            // xhr.onerror = function (e) {
            //     callback('获取签名出错');
            // };
            // xhr.send();

            // 方法二（适用于前端调试），需要引入../dist/cos-js-sdk-v5.min.js
            var authorization = COS.getAuthorization({
                SecretId: 'AKID78zgDYbgS2V1OcbWDh1GJCxnU2OXeKxO',
                SecretKey: 'fHsOiplU1MYYAbu55uXzMXWKwMako8KR',
                Method: options.Method,
                Key: options.Key,
            });
            callback(null, authorization);
        };

        // 上传文件
        
            var Key = file.name;

            getAuthorization({Method: 'POST', Key: ''}, function (err, auth) {
                var fd = new FormData();
                fd.append('key', Key);
                fd.append('Signature', auth);
                fd.append('success_action_status', '200');
                fd.append('file', file);

                var url = prefix;
                var xhr = new XMLHttpRequest();
                xhr.open('POST', url, true);
                xhr.onload = function () {
                    if (xhr.status === 200 || xhr.status === 206) {
                        var ETag = xhr.getResponseHeader('etag');
                        callback(null, {url: url, ETag: ETag});
                    } else {
                        callback('文件 ' + Key + ' 上传失败，状态码：' + xhr.status);
                    }
                };
                xhr.onerror = function () {
                    callback('文件 ' + Key + ' 上传失败，请检查是否没配置 CORS 跨域规则');
                };
                xhr.send(fd);
            });
     

        
       
    }
   
}
